<?php

namespace app\index\controller;

use think\Request;
use think\Db;

class Tellermanagement extends Common
{
    //柜员管理
    public function gygl()
    {
        $data = input();
        if (empty($data['name'])) {
            $name = $data['name'] = '';
        } else {
            $name = trim($data['name']);
        }
        if (empty($data['fytype'])) {
            $fytype = $data['fytype'] = '';
        } else {
            $fytype = $data['fytype'];
        }
        if (empty($data['jujian'])) {
            $jujian = $data['jujian'] = '';
        } else {
            $jujian = $data['jujian'];
        }
        if (empty($data['money'])) {
            $money = $data['money'] = '';
        } else {
            $money = $data['money'];
        }
        $id = $this->id;
        if ($this->isCZY) {
            $id = $this->jujian['par_id'];
        }
//        $page = input('page/d') ? input('page/d') : 1;
//        $limit = input('limit/d') ? input('limit/d') : 20;
        $hb = db('huobi')->where('bz', 1)->column('id');
        $where['jb.hb_id'] = ['in', $hb];
        $where['j.bz'] = '1';
        $where['lb_id'] = ['lt', 3];
        $where['jb.hb_id'] = ['in', $hb];
        if (!empty($data['name'])) {
            $where['j.xingming|j.bh'] = ['like', "%" . $name . "%"];
        }
        if (!empty($data['fytype'])) {
            $where['fl.name'] = ['like', "%" . $fytype . "%"];;
        }
        $or = '';
        if ($jujian) {
            $jujian = trim($jujian, ',');
            $jujian = explode(',', $jujian);
            if (count($jujian) >= 1) {
                if (count($jujian) == 1) {
                    //判断选择的是不是自己
                    if ($jujian[0] == $this->id) {
                        $where['j.id'] = $jujian[0];
                    } else {
                        $where['j.sj_xulie'] = ['like', "%,$jujian[0],%"];
                    }
                } else {
                    foreach ($jujian as $k => $v) {
                        if ($k == 0) {
                            $or .= "j.sj_xulie like '%,$v,%'";
                        } else {
                            $or .= " or j.sj_xulie like '%,$v,%' or j.id = '$id'";
                        }
                    }
                }
            }
        } else {
//            $where['j.sj_xulie'] = ['like',"%,$id,%"];
            $or .= "j.sj_xulie like '%,$id,%'  or j.id = '$id'";
        }
        if (!empty($data['money'])) {
            $where['h.name'] = ['like', "%" . $money . "%"];;
        }
        $result_jujian = db('jujian')
            ->alias('j')
            ->where($where)
            ->where($or)
            ->field('j.id as id,j.fzr_bh,jb.id as jbid,j.sj_xulie as guanxi,j.bh as zhanghuming,xingming as gongsimingcheng,fzr_name as fuzerenxingming,tel as phone,jl.name as dltype,yonghu_num as shuliangxianzhi,f.name as cbmoban,hz.name as hlmoban,h.name as bizhong,jb.jine as jbzhanghu,jb.yongjin_jine as yjzhanghu,jb.zong_yongjin as zyj,fl.name as fanyongleibie,tuiguang')
            ->join('jujian_lb jl', 'j.lb_id = jl.id', 'LEFT')
            ->join('fee_jujian_zu f', 'j.fee_zu_id = f.id', 'LEFT')
            ->join('toucun_zu t', 'j.toucun_zu_id = t.id', 'LEFT')
            ->join('jujian_bian jb', 'j.id = jb.yh_id', 'LEFT')
            ->join('huobi h', 'h.id = jb.hb_id', 'LEFT')
            ->join('huobi_zu hz', 'hz.id=j.hb_zu_id', 'LEFT')
            ->join('fanyong_lb fl', 'fl.id =  t.fanyong_lb', 'LEFT')
            ->order('j.bh', 'asc')
            ->select();
        foreach ($result_jujian as $k => $v) {
            $result_jujian[$k]['guanxi'] = $this->get_dl_name($v['guanxi']);
        }
        if (!empty($result_jujian)) {
            returnSuccess($result_jujian);
            die;
        }
        returnError('未查到数据');

    }

    //数据
    public function shuju()
    {
        $data = input();
        //选取ID为2的普通柜员
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $bjdl_id = db('jujian')->where('id', $user_id)->find();
        //选取ID为2的普通柜员
        $daili = db('jujian_lb')->where('id', 2)->select();
        $gt_jujian_id = db('jujian')
            ->where('id', $user_id)
            ->value('gt_jujian_id');
        $sheng = db('sheng')->select();
        $yihang = db('bank')->select();
        $chengben = db('fee_jujian_zu')
            ->where('ib_id', $gt_jujian_id)
            ->where('bz', 1)
            ->select();
        $huilv = db('huobi_zu')
            ->where('ib_id', $gt_jujian_id)
            ->where('bz', 1)
            ->select();
        $toucun = db('toucun_zu')
            ->where('ib_id', $gt_jujian_id)
            ->where('bz', 1)
            ->select();
        $chujin = db('chujin_zu')
            ->where('ib_id', $gt_jujian_id)
            ->where('bz', 1)
            ->select();
        $rujin = db('rujin_zu')
            ->where('ib_id', $gt_jujian_id)
            ->where('bz', 1)
            ->select();
        if ($bjdl_id['par_id'] == 0) {
            $result = array($daili, $sheng, $yihang, $chengben, $huilv, $toucun, $rujin, $chujin);
        } else {
            $jujian_old = db('jujian')
                ->where('id', $user_id)
                ->find();

            $sheng_old = db('sheng')
                ->where('id', $jujian_old['sheng_id'])
                ->select();
            $shi_old = db('shi')
                ->where('id', $jujian_old['shi_id'])
                ->select();

            $yihang_old = db('bank')
                ->where('id', $jujian_old['bank_id'])
                ->select();

            $chengben_old = db('fee_jujian_zu')
                ->where('id', $jujian_old['fee_zu_id'])
                ->select();

            $huilv_old = db('huobi_zu')
                ->where('id', $jujian_old['hb_zu_id'])
                ->select();

            $toucun_old = db('toucun_zu')
                ->where('id', $jujian_old['toucun_zu_id'])
                ->select();

            $chujin_old = db('chujin_zu')
                ->where('id', $jujian_old['chujin_zu_id'])
                ->select();

            $rujin_old = db('rujin_zu')
                ->where('id', $jujian_old['rujin_zu_id'])
                ->select();
            $result = array($daili, $sheng, $yihang, $chengben, $huilv, $toucun, $rujin, $chujin, $sheng_old, $shi_old, $yihang_old, $chengben_old, $huilv_old, $toucun_old, $rujin_old, $chujin_old);
        }
        returnSuccess(['data' => $result]);
        die;
    }

    //获取市
    public function shi()
    {
        $data = input();
        if (empty($data['sheng_id'])) {
            returnError('参数不正确');
        }
        preg_match('/\d+/', $data['sheng_id'], $sheng_id);
        $result = db('shi')->where('sheng_id', $sheng_id[0])->select();
        if ($result) {
            returnSuccess($result);
            die;
        }
        returnError('未查到数据');
    }

    //代理转挂数据
    public function dlzg_shuju()
    {
        $data = input();
        $result = db('jujian')->where('id', $data['bjdl_id'])->find();
        $sjbh = db('jujian')->where('id', $result['par_id'])->value('bh');
        if (!empty($sjbh)) {
            returnSuccess($sjbh);
            die;
        }
        returnError('未查到数据');
    }

    public function cbmb_sxf_check(Request $request)
    {
        $data = input();
        $par_name = strtoupper($data['par']);
        preg_match('/\d+/', $data['fee_zu_id'], $fee_zu_id);
        //下级成本模板id
        $xj_fee_zu_id = $fee_zu_id[0];
        $sjdl = db('jujian')
            ->where('bh', $par_name)
            ->find();
        if (count($sjdl) > 0) {
            //上级成本模板id
            $sj_fee_zu_id = $sjdl['fee_zu_id'];
            if ($sj_fee_zu_id == $xj_fee_zu_id) {
                returnError('你不能选择此成本模板，换一个');
            }
            $sj_sxf = db('fee_jujian_zu_detail')
                ->where('fee_zu_id', $sj_fee_zu_id)
                ->where('toucun_bili', 'neq', 0)
                ->field('heyue_zu_id,toucun_bili')
                ->order('heyue_zu_id')
                ->select();
            $arr_yi = array();
            foreach ($sj_sxf as $key => $k_value) {
                $arr_yi[$key] = $sj_sxf[$key]['heyue_zu_id'];
            }
            $xj_sxf = db('fee_jujian_zu_detail')
                ->where('fee_zu_id', $xj_fee_zu_id)
                ->where('toucun_bili', 'neq', 0)
                ->where('heyue_zu_id', 'in', $arr_yi)
                ->field('heyue_zu_id,toucun_bili')
                ->order('heyue_zu_id')
                ->select();
        } else {
            returnError('上级代理不存在');
        }
        returnSuccess($xj_sxf);
    }
    /**
     * 添加代理提交接口
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    //添加代理
    public function addAgentRequest()
    {
        $lb_id = input('lb_id/d');
        $gongsiName = input('gongsiName');
        $fuzeren = input('fuzeren');
        $pass = input('pass');
        $tel = input('tel/d');
        $userNum = input('userNum');
        $shenfenzhengNum = input('shenfenzhengNum');
        $sheng_id = input('sheng_id/d');
        $shi_id = input('shi_id/d');
        $bank_id = input('bank_id/d');
        $dizhi = input('dizhi');
        $bank_bh = input('bank_bh/d');
        $par_bh = input('par_bh');
        $fee_zu_id = input('fee_zu_id/d', 1);
        $hb_zu_id = input('hb_zu_id/d', 1);
        $tcmb = input('tcmb/d', 1);
        $rjmb = input('rjmb/d', 1);
        $cjmb = input('cjmb/d', 1);
        $fanyong_lb = input('fanyong_lb/d', 2);
        if (!$lb_id || !$gongsiName || !$fuzeren || !$pass || !$tel || !$userNum || !$shenfenzhengNum || !$sheng_id || !$shi_id || !$bank_id || !$dizhi || !$bank_bh || !$par_bh) {
            returnError('缺少参数');
        }
        $par_jujian = db('jujian')->where('bh', $par_bh)->find();
        if (!$par_jujian) {
            returnError('上级不存在');
        }
        //判断是否有权限
        $sj_id_arr = explode(',', $par_jujian['sj_xulie']);

        $id = $this->id;
        $bh = $this->jujian['bh'];
        if ($this->isCZY) {
            $id = $this->jujian['par_id'];
            $bh = db('jujian')->where('id', $id)->value('bh');
        }

        if (!in_array($id, $sj_id_arr) && $bh != $par_bh) {
            returnError('当前登录账户无权限添加到编号' . $par_bh . '下');
        }
        if ($lb_id != 2) {
            returnError('只能添加普通代理');
        }
        if (substr($par_bh, 0, 3) == 'CZY') {
            returnError('上级不可为操作员');
        }
        $par_length = strlen($par_bh);
        //判断如果是2
        $num = 0;
        for ($i = 0; $i < $par_length; $i++) {
            $n = substr($par_bh, $i, 1);
            if (is_numeric($n)) {
                $num++;
            }
        }
        if ($num == 0) {
            $max_bh = db('jujian')->where("`bh` like '$par_bh%' and length(`bh`) = ($par_length+2)")->order('bh', 'desc')->value('bh');
            if (empty($max_bh)) {
                $new_bh = $par_bh . "01";
            } else {
                $for_bh = substr($max_bh, $par_length);
                for ($i = 1; $i <= 99; $i++) {
                    $for_bh++;
                    if ($for_bh > 99) {
                        returnError('该上级代理下级代理已经超过最大数量99！');
                    }
                    $for_bh += 100;
                    $for_bh = substr($for_bh, 1);
                    if (strpos($for_bh, '4') === false) { //不要4
                        $new_bh = $par_bh . $for_bh;
                        break;
                    }
                }
            }
        } elseif ($num == 2) {
            $max_bh = db('jujian')->where("`bh` like '$par_bh%' and length(`bh`) = ($par_length+3)")->order('bh', 'desc')->value('bh');
            if (empty($max_bh)) {
                $new_bh = $par_bh . "001";
            } else {
                $for_bh = substr($max_bh, $par_length);
                for ($i = 1; $i <= 999; $i++) {
                    $for_bh++;
                    if ($for_bh > 999) {
                        returnError('该上级代理下级代理已经超过最大数量999！');
                    }
                    $for_bh += 1000;
                    $for_bh = substr($for_bh, 1);
                    if (strpos($for_bh, '4') === false) { //不要4
                        $new_bh = $par_bh . $for_bh;
                        break;
                    }
                }
            }
        } elseif ($num == 5) {
            $for_bh_name = substr($par_bh,0,$par_length-3);

            $max_bh = db('jujian')->where("`bh` like '$for_bh_name%' and length(`bh`) =$par_length")->order('bh', 'desc')->value('bh');

            $for_bh = substr($max_bh, -3);

            for ($i = 1; $i <= 999; $i++) {
                $for_bh++;
                if ($for_bh > 999) {
                    returnError('该上级代理下级代理已经超过最大数量999！');
                }
                $for_bh = 1000+$for_bh;
                $for_bh = substr($for_bh, 1);
                if (strpos($for_bh, '4') === false) { //不要4
                    $new_bh = substr($max_bh, 0, strlen($max_bh) - 3) . $for_bh;
                    break;
                }
            }
        } else {
            returnError('无法生成代理编号，请更换上级编号重试');
        }

        if (!$new_bh) {
            returnError('无法生成代理编号，请更换上级编号重试');
        }
        $jujian_id = $par_jujian['id'];
        $zishen_sj_xulie = "," . $par_jujian['id'] . $par_jujian['sj_xulie'];
        $shuju = array( 'gt_jujian_id' => $par_jujian['gt_jujian_id'], 'bh' => $new_bh, 'lb_id' => $lb_id, 'xingming' => $gongsiName, 'fzr_name' => $fuzeren, 'passwd' => MD5($pass), 'tel' => $tel, 'yonghu_num' => $userNum, 'fzr_bh' => $shenfenzhengNum, 'sheng_id' => $sheng_id, 'shi_id' => $shi_id, 'bank_id' => $bank_id, 'dizhi' => $dizhi, 'bank_bh' => $bank_bh, 'fee_zu_id' => $fee_zu_id, 'hb_zu_id' => $hb_zu_id, 'toucun_zu_id' => $tcmb, 'rujin_zu_id' => $rjmb, 'chujin_zu_id' => $cjmb, 'par_id' => $jujian_id, 'sj_xulie' => $zishen_sj_xulie, 'bz' => 0);
        //开启事务
        //开启事务
        Db::startTrans();
        //插入用户表
        $jid = db('jujian')->insertGetId($shuju);
        if ($jid > 0) {
            //货币
            $jujian_bian_shuju = array(
                ['yh_id' => $jid, 'hb_id' => 1],
                ['yh_id' => $jid, 'hb_id' => 2],
                ['yh_id' => $jid, 'hb_id' => 3],
                ['yh_id' => $jid, 'hb_id' => 4]
            );
            $result = db('jujian_bian')->insertAll($jujian_bian_shuju);
            if ($result == 4) {
                Db::commit();
                returnSuccess('添加成功！');
            } else {
                Db::rollback();
                returnError('添加失败，请重试~！');
            }
        } else {
            Db::rollback();
            returnError('添加失败，请重试~！');
        }
        //记录日志功能
        $this->riZhi(29, ['添加代理' => '成功', '代理ID' => $jid, '代理编号' => $new_bh, '代理姓名' => $gongsiName, '负责人姓名' => $fuzeren], ['teller_add' => '1']);
    }

    //代理转挂
    //代理转挂
    public function dlzg()
    {
        $data = input();
        if (empty($data['par_bh'])) {
            returnError('参数错误');
        }
        if (empty($data['bh'])) {
            returnError('参数错误');
        }
        $have = db('jujian')->where('bh', $data['par_bh'])->find();
        $xiaji = db('jujian')->where('bh', $data['bh'])->find();
        if (!$xiaji) {
            returnError('当前代理不存在！');
        }
        if (!empty($have)) {
            if (strtoupper(substr($have['bh'], 0, 3)) == 'CZY') {
                returnError('上级不可为操作员！');
            }
            $leader_xulei = explode(',', $have['sj_xulie']);
            if ($have['id'] == $xiaji['id']) {
                returnError('上级代理不能为自己！');
            }
            if (array_search($xiaji['id'], $leader_xulei) > 0) {
                returnError('代理不能转挂至子类及以下代理，请重新填写!');
            }
            if ($xiaji['par_id'] == $have['id']) {
                returnError('上级代理未做修改，请重新填写!');
            }
            if ($xiaji['gt_jujian_id'] != $have['gt_jujian_id']) {
                returnError('不属于同一柜员，请重新填写!');
            }
//            $parentZuIds = $have['fee_zu_id'];
//            if ($parentZuIds) {
//                $parent_fee_zu_rows = Db::name('fee_jujian_zu_detail')
//                    ->where('fee_zu_id', $parentZuIds)
//                    ->select();
//                $chengben_id = db('jujian')
//                    ->where('bh', $data['bh'])
//                    ->value('fee_zu_id');
//                $fee_zu_rows = Db::name('fee_jujian_zu_detail')
//                    ->where('fee_zu_id', $chengben_id)
//                    ->select();
//
//                $parent_fee_zu_rows_new = $fee_zu_rows_new = [];
//                foreach ($parent_fee_zu_rows as $k => $v) {
//                    $parent_fee_zu_rows_new[$v['heyue_zu_id']] = $v;
//                }
//                foreach ($fee_zu_rows as $k => $v) {
//                    $fee_zu_rows_new[$v['heyue_zu_id']] = $v;
//                }
//                foreach ($parent_fee_zu_rows_new as $k => $v) {
//                    if (array_key_exists($k, $fee_zu_rows_new)) {
//                        if ($fee_zu_rows_new[$k]['jian_yongjin'] < $v['jian_yongjin'] ||
//                            $fee_zu_rows_new[$k]['ping_jin_yongjin'] < $v['ping_jin_yongjin'] ||
//                            $fee_zu_rows_new[$k]['ping_zuo_yongjin'] < $v['ping_zuo_yongjin'] ||
//                            $fee_zu_rows_new[$k]['toucun_bili'] < $v['toucun_bili']) {
//                            returnError('成本模板不能小于上级！请重新选择');
//                        }
//                    }
//                }
//            }
            $arr = [];
            $arr['par_id'] = $have['id'];
            if ($have['par_id'] == 0) {
                $arr['sj_xulie'] = ',' . $have['id'] . ',';
            } else {
                $arr['sj_xulie'] = ',' . $have['id'] . $have['sj_xulie'];
            }

            $res = db('jujian')
                ->where('bh', $data['bh'])
                ->update($arr);
            if ($res) {
                //更新当前代理所有下级代理,用户
                $sql1 = "update jujian set sj_xulie = REPLACE(sj_xulie,'{$xiaji['sj_xulie']}','{$arr['sj_xulie']}') where sj_xulie like '%,{$xiaji['id']},%'";
                $sql2 = "update yonghu set sj_xulie = REPLACE(sj_xulie,'{$xiaji['sj_xulie']}','{$arr['sj_xulie']}') where sj_xulie like '%,{$xiaji['id']},%'";
                db()->execute($sql1);
                db()->execute($sql2);
                $operation_category = 27;
                $detail_name = array('代理转挂', '操作者ID', '代理编号', '转挂后代理编号');
                $operation_value = array('成功', $this->id, $data['bh'], $data['par_bh']);
                $re_name = 'teller_edit';
                $re_value = '1';
                $rizhi = new Rizhi();
                $jieguo = $rizhi->index($this->id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
                returnSuccess($jieguo);
                die;
            } else {
                returnError('您未做任何修改');
            }
        } else {
            returnError('上级代理不存在，请重新填写!');
        }
    }
    public function tzyjzh_sj(){
        $data = input();
        if (empty($data['bjdl_id'])) {
            returnError('代理ID参数错误');
        }
        if (empty($data['hb_id'])) {
            returnError('货币参数错误');
        }
        $result = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'j.id=jb.yh_id')
            ->join('huobi h', 'h.id=jb.hb_id')
            ->where('j.id', $data['bjdl_id'])
            ->where('h.name', $data['hb_id'])
            ->field('jb.id,j.bh,j.xingming,h.name,jb.yongjin_jine as yue')
            ->find();
        if (!empty($result)) {
            returnSuccess($result);
            die;
        }
        returnError('未查到数据');
    }
    //调整佣金账户
    public function tzyjzh()
    {
        $data = input();
        $lb_id = 3;
        if (empty($data['id'])) {
            returnError('id不能为空');
        }
        if(is_float($data['tzhye'])){
            $data['tzhye'] = round($data['tzhye'],2);
        }

        if (empty($data['hb_id'])) {
            returnError('货币编号不能为空');
        }
        $info = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'jb.yh_id=j.id')
            ->where('jb.id', $data['id'])
            ->field('jb.yh_id,j.bh,j.xingming,j.id')
            ->find();
        $huobi_id = db('huobi')->where('name', $data['hb_id'])->value('id');
        $money = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->value('yongjin_jine');
        if ($money == $data['tzhye']) {
            returnError('修改失败，请检查您的金额是否修改');
        }
        $money = $data['tzhye'] - $money;
        $result = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->update(['yongjin_jine' => $data['tzhye']]);
        //加入流水
        Db::startTrans();
        $res['yh_id'] = $info['yh_id'];
        $res['lb'] = $lb_id;//3调整
        $res['hb_id'] = $huobi_id;
        $res['jine'] = $money;
        $res['yue'] = $data['tzhye'];
        $res['shijian'] = time();
        $res['zh_lb'] = '3';
        $c = db('jujian_liushui')->insertGetId($res);
        if ($result && $c) {
            Db::commit();
        } else {
            Db::rollback();
            returnError('调整失败');
        }
        if ($c) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 106;
            $detail_name = array('调整基本账户', '代理ID', '代理编号', '代理姓名', '货币ID', '调整后余额');
            $operation_value = array('成功', $info['yh_id'], $info['id'], $info['xingming'], $data['hb_id'], $data['tzhye']);
            $re_name = 'tzyxyjzh_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if ($res['code']) {
                returnSuccess($res);
            }
        } else {
            returnError('调整失败');
        }
    }

    //调整基本账户
    public function tzjbzh_sj()
    {
        $data = input();
        if (empty($data['bjdl_id'])) {
            returnError('代理ID参数错误');
        }
        if (empty($data['hb_id'])) {
            returnError('货币参数错误');
        }
        $result = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'j.id=jb.yh_id')
            ->join('huobi h', 'h.id=jb.hb_id')
            ->where('j.id', $data['bjdl_id'])
            ->where('h.name', $data['hb_id'])
            ->field('jb.id,j.bh,j.xingming,h.name,jb.jine as yue')
            ->find();
        if (!empty($result)) {
            returnSuccess($result);
            die;
        }
        returnError('未查到数据');
    }

    //提交调整基本账户
    public function tzjbzh()
    {
        $data = input();
        $lb_id = 3;
//         if (config('web_name') == 'HC'){
//             $lb_id = input('lb_id',3,'intval');
//         }
        if (empty($data['id'])) {
            returnError('id不能为空');
        }
//        if (empty($data['tzhye']) || $data['tzhye'] < 0) {
//            returnError('调整金额不能为空或调整后的金额不能为负');
//        }
        if(is_float($data['tzhye'])){
            $data['tzhye'] = round($data['tzhye'],2);
        }

        if (empty($data['hb_id'])) {
            returnError('货币编号不能为空');
        }
        $info = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'jb.yh_id=j.id')
            ->where('jb.id', $data['id'])
            ->field('jb.yh_id,j.bh,j.xingming,j.id')
            ->find();
        $huobi_id = db('huobi')->where('name', $data['hb_id'])->value('id');
        $money = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->value('jine');
        if ($money == $data['tzhye']) {
            returnError('修改失败，请检查您的金额是否修改');
        }
        $money = $data['tzhye'] - $money;
        $result = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->update(['jine' => $data['tzhye']]);
        //加入流水
        Db::startTrans();
        $res['yh_id'] = $info['yh_id'];
        $res['lb'] = $lb_id;//3调整
        $res['hb_id'] = $huobi_id;
        $res['jine'] = $money;
        $res['yue'] = $data['tzhye'];
        $res['shijian'] = time();
        $res['zh_lb'] = '1';
        $c = db('jujian_liushui')->insertGetId($res);
        if ($result && $c) {
            Db::commit();
        } else {
            Db::rollback();
            returnError('调整失败');
        }
        if ($c) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 106;
            $detail_name = array('调整基本账户', '代理ID', '代理编号', '代理姓名', '货币ID', '调整后余额');
            $operation_value = array('成功', $info['yh_id'], $info['id'], $info['xingming'], $data['hb_id'], $data['tzhye']);
            $re_name = 'tzyxyjzh_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if ($res['code']) {
                returnSuccess($res);
            }
        } else {
            returnError('调整失败');
        }
    }

    //调整有效佣金账户提交
    public function tzyxyjzh_sj()
    {
        $data = input();
        if (empty($data['bjdl_id'])) {
            returnError('编辑代理id不能为空');
        }
        if (empty($data['hb_id'])) {
            returnError('货币id不能为空');
        }
        $result = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'j.id=jb.yh_id')
            ->join('huobi h', 'h.id=jb.hb_id')
            ->where('j.id', $data['bjdl_id'])
            ->where('h.name', $data['hb_id'])
            ->field('jb.id,j.bh,j.xingming,h.name,jb.zong_yongjin')
            ->find();
        if (!empty($result)) {
            returnSuccess($result);
            die;
        }
        returnError('未查到数据');

    }

    //调整有效佣金账户
    public function tzyxyjzh()
    {
        $data = input();
        $lb_id = 3;
        if (config('web_name') == 'HC'){
            $lb_id = input('lb_id',3,'intval');
        }
        $data['tzhye'] = input('tzhye');
        if(is_float($data['tzhye'])){
            $data['tzhye'] = round($data['tzhye'],2);
        }
        if (empty($data['id'])) {
            returnError('id不能为空');
        }
//        if (empty($data['tzhye']) || $data['tzhye'] < 0) {
//            returnError('调整金额不能为空或调整金额不能为负');
//        }
        if (empty($data['hb_id'])) {
            returnError('货币编号不能为空');
        }
        $huobi_id = db('huobi')->where('name', $data['hb_id'])->value('id');
        $money = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->value('zong_yongjin');
        $info = db('jujian_bian')
            ->alias('jb')
            ->join('jujian j', 'jb.yh_id=j.id')
            ->where('jb.id', $data['id'])
            ->field('jb.yh_id,j.bh,j.xingming,j.id')
            ->find();
        $result = db('jujian_bian')->where('id', $data['id'])->where('hb_id', $huobi_id)->update(['zong_yongjin' => $data['tzhye']]);
        //加入流水
        $res['yh_id'] = $info['yh_id'];
        $res['lb'] = $lb_id;//3调整
        $res['hb_id'] = $huobi_id;
        $res['jine'] = $data['tzhye'] - $money;
        $res['yue'] = $data['tzhye'];
        $res['shijian'] = time();
        $res['zh_lb'] = '2';
        $c = db('jujian_liushui')->insertGetId($res);
        if ($result && $c) {
            Db::commit();
        } else {
            Db::rollback();
            returnError('调整失败');
        }
        if ($result > 0) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 110;
            $detail_name = array('调整有效佣金账户', '代理ID', '代理编号', '代理姓名', '货币ID', '调整后余额');
            $operation_value = array('成功', $info['yh_id'], $info['bh'], $info['xingming'], $data['hb_id'], $data['tzhye']);
            $re_name = 'tzyxyjzh_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $jieguo = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if (!empty($jieguo)) {
                returnSuccess($jieguo);
                die;
            }
        } else {
            returnError('调整失败');
        }
    }

    //编辑返佣类别提交
    public function bjfylb_sj(Request $request)
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError('bjdl_id不能为空');
        }
        $result_jujian = db('jujian')->where('id', $data['bjdl_id'])->field('id,bh,xingming')->find();
        if (empty($result_jujian)) {
            returnError('未查到数据');
        }
        $result_fanyong_lb = db('fanyong_lb')->select();
        $result_jujian['fanyong'] = $result_fanyong_lb;
        $result = array($result_jujian);
        returnSuccess($result);
    }

    //提交返佣类别
    public function bjfylb()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        $data['fanyong_lb'] = input('fanyong_lb/d');

        if (empty($data['bjdl_id'])) {
            returnError('编辑代理id不能为空');
        }
        if (empty($data['fanyong_lb'])) {
            returnError('返佣类别id不能为空');
        }
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['fanyong_lb' => $data['fanyong_lb']]);
        if ($result) {
            $this->riZhi(107, ['编辑返佣类别' => '成功', '操作人员' => $this->jujian['bh'], '返佣类别' => $data['fanyong_lb']], ['user_add' => '1']);
            returnSuccess($result);
        } else {
            $res = db('fanyong_lb')->where('id', $data['fanyong_lb'])->value('name');
            returnError("调整失败,您当前的返佣类别为:{$res}");
        }
    }

    //重置密码
    public function czmm()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError('编辑代理ID不能为空');
        }
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['passwd' => md5(888888)]);
        if ($result > 0) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 109;
            $detail_name = array('修改代理或操作员密码', '代理ID', '密码');
            $operation_value = array('成功', $data['bjdl_id'], '888888');
            $re_name = 'tell_passwd_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($this->id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
        }

        if (!empty($res)) {
            returnSuccess($res);
        } else {
            returnError('重置密码失败');
        }
    }

    //删除代理
    public function scdl()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError('编辑代理ID不能为空');
        }
        $yonghu = db('jujian')->where('id', $data['bjdl_id'])->find();
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['bz' => 3]);
        if ($result > 0) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 59;
            $detail_name = array('删除代理', '代理ID', '代理编号', '代理姓名');
            $operation_value = array('成功', $data['bjdl_id'], $yonghu['bh'], $yonghu['xingming']);
            $re_name = 'teller_delete';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
        }
        if (!empty($res)) {
            returnSuccess($res);
        } else {
            returnError('删除代理失败');
        }
    }

    //在线代理
    public function zxdl()
    {
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $where = "(y.sj_xulie like '%,$user_id,%' or y.id=$user_id)";
        $requert = db('zaixian')
            ->alias('z')
            ->join('jujian y', 'z.yh_id=y.id', 'LEFT')
            ->where('z.lb', 2)
            ->where($where)
            ->field('z.*,y.xingming')
            ->select();

        if (!empty($requert)) {
            returnSuccess($requert);
        } else {
            returnError('暂无数据');
        }
    }

    //代理回收站
    public function dlhsz()
    {
        if ($this->isCZY) {
            $jujian_id = $this->par_id;
        } else {
            $jujian_id = $this->id;
        }
        $requert = db('jujian')
            ->where('sj_xulie', 'like', "%," . $jujian_id . ",%")
            ->where('bz', 3)
            ->field('id,bh,xingming,tel')
            ->select();
        if (!empty($requert)) {
            returnSuccess($requert);
        } else {
            returnError('暂无数据');
        }
    }

    //代理回收站恢复
    public function dlhsz_hf()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError(['data' => '', 'msg' => '编辑代理ID不能为空']);
        }
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['bz' => 1]);
        $jujian = db('jujian')
            ->where('id', $data['bjdl_id'])
            ->field('bh,xingming')
            ->find();
        if ($result > 0) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 101;
            $detail_name = array('恢复代理', '代理ID', '代理编号', '代理姓名');
            $operation_value = array('成功', $data['bjdl_id'], $jujian['bh'], $jujian['xingming']);
            $re_name = 'tell_turn';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
        }
        if (!empty($res)) {
            returnSuccess($res);
        } else {
            returnError('代理恢复失败');
        }
    }

    //代理操作日志  需要加分页
    public function dlczrz()
    {
        $data = input();
        if (empty($data['name'])) {
            $name = $data['name'] = '';
        } else {
            $name = trim($data['name']);
        }
        if (empty($data['czzl'])) {
            $czzl = $data['czzl'] = '';
        } else {
            $czzl = $data['czzl'];
        }
        if (empty($data['qujian'])) {
            $jujian = '';
        } else {
            $jujian = $data['qujian'];
        }
        $page = input('page/d') ? input('page/d') : 1;
        $limit = input('limit/d') ? input('limit/d') : 20;
        if (!$this->isCZY) {
            $and = "(ju.sj_xulie like '%,$this->id,%' or ju.id = $this->id)";
        }else{
            $and = "ju.gt_jujian_id = {$this->jujian['gt_jujian_id']}";
        }
        if (!empty($data['date_start'])) {
            $date_start = strtotime($data['date_start']);
        } else {
            $date_start = strtotime(date('Y-m-d 00:00:00', time()));
        }
        if (!empty($data['date_end'])) {
            $date_end = strtotime('+23 hours 59 minute 59 seconds', strtotime($data['date_end']));
        } else {
            $date_end = strtotime(date('Y-m-d 23:59:59', time()));
        }
        $where['o.operation_time'] = ['between time', [(int)$date_start, (int)$date_end]];
        $where['o.user_category'] = '2';
        if (!empty($name)) {
            $where['ju.bh|ju.xingming|ju.tel'] = ['like', "%" . $name . "%"];
        }
        if (!empty($czzl)) {
            $czzl_id = db('operation_records_category')->where('name', $czzl)->value('id');
            $where['o.operation_category'] = ['like', "%" . $czzl_id . "%"];
        }
        $or = '';
        if (!empty($jujian)) {
            $jujian = trim($jujian, ',');
            $jujian = explode(',', $jujian);
            if (count($jujian) >= 1) {
                if (count($jujian) == 1) {
                    //判断选择的是不是自己
                    if ($jujian[0] == $this->id) {
                        $where['ju.id'] = $jujian[0];
                    } else {
                        $or = " (ju.sj_xulie like '%,$jujian[0],%' or ju.id = '$jujian[0]')";
                    }
                } else {
                    foreach ($jujian as $k1 => $v1) {
                        if ($k1 == 0) {
                            $or .= " (ju.sj_xulie like '%,$v1,%' or ju.id = '{$jujian[0]}'";
                        } else {
                            $or .= " or ju.sj_xulie like '%,$v1,%' or ju.id = '{$jujian[$k1]}'";
                        }
                    }
                    if ($or != '') {
                        $or .= ')';
                    }
                }
            }
        }
        else {
//            $where['j.sj_xulie'] = ['like',"%,$id,%"];
//            $or .= " (ju.sj_xulie like '%,$dl_yh_id,%'  or ju.id = '$dl_yh_id')";
        }



        $result_operation_records_count = db('operation_records')
            ->alias('o')
            ->join('jujian ju', 'ju.id=o.user_id', 'LEFT')
            ->join('operation_records_category ca', 'o.operation_category = ca.id', 'LEFT')
            ->where($where)
            ->where($and)
            ->where($or)
            ->field('o.id,o.ip,o.operation_time as time,ju.sj_xulie as dlgx,ju.bh as zhanghu,ju.xingming,ca.name')
            ->count();
        $result_operation_records = db('operation_records')
            ->alias('o')
            ->join('jujian ju', 'ju.id=o.user_id', 'LEFT')
            ->join('operation_records_category ca', 'ca.id =o.operation_category', 'LEFT')
            ->where($where)
            ->where($or)
            ->where($and)
            ->field('o.id,o.ip,o.operation_time as time,ju.sj_xulie as dlgx,ju.bh as zhanghu,ju.xingming,ca.name')
            ->page($page, $limit)
            ->select();
        if (!empty($result_operation_records)) {
            foreach ($result_operation_records as $k => $v) {
                $result_operation_records[$k]['dlgx'] = $this->get_dl_name($v['dlgx']);
            }
            $jieguo['res'] = $result_operation_records;
            $jieguo['count'] = $result_operation_records_count;
            returnSuccess($jieguo);
        } else {
            returnError('暂无数据');
        }

    }

    //代理操作日志详情
    public function dlczrz_xq()
    {
        $data = input();
        $data['id'] = input('id/d');
        if (empty($data['id'])) {
            returnError('请选择要查看的详情ID');
        }
        $result = db('operation_records_detail')->where('par_id', $data['id'])->field('detail_name as czmc,operation_value as czz')->select();
        if (!empty($result)) {
            returnSuccess($result);
        } else {
            returnError('暂无数据');
        }
    }

    //操作员管理
    public function czygl()
    {
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $result_guanli = db('jujian')
            ->alias('j')
            ->join('jujian_lb jl', 'j.lb_id=jl.id')
            ->where('j.lb_id', '>', 2)
            ->where('j.par_id', $user_id)
            ->field('j.id as xzid,j.bh,j.xingming,j.tel,jl.name,jl.id as jid')
            ->select();
        if (!empty($result_guanli)) {
            returnSuccess($result_guanli);
        } else {
            returnError('暂无数据');
        }
    }

    //操作员管理提交数据
    public function czygl_tj_shuju()
    {
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $result_guanli_lb = db('jujian_lb')
            ->where('bz', 1)
            ->where('jujian_id', $user_id)
            ->field('id,name')
            ->select();
        if (!empty($result_guanli_lb)) {
            returnSuccess($result_guanli_lb);
        } else {
            returnError('暂无数据');
        }
    }

    //操作员管理提交
    public function czygl_tj(Request $requert)
    {
        $data = input();
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $data['tel'] = input('tel/d');
        if (empty($data['tel'])) {
            returnError('请输入手机号');
        }
        $data['qx'] = input('qx/d');
        if (empty($data['qx'])) {
            returnError('权限模板ID不能为空');
        }
        $tel_all = db('jujian')
            ->where('tel', $data['tel'])
            ->where('sj_xulie', 'like', "%," . $user_id . ",%")
            ->count();
        if ($tel_all > 0) {
            returnError('该手机号码已被注册');
        }
        $czy_all = db('jujian')
            ->where('bh', 'like', 'CZY' . '%')
            ->field('bh')
            ->select();
        foreach ($czy_all as $key => $k_value) {
            $czy_all[$key] = substr($k_value['bh'], 3);
        }
        for ($i = 1; $i < 1000; $i++) {
            $czy_add = sprintf('%03s', $i);
            //带4的过滤，继续执行
            if (strstr($czy_add, '4')) {
                continue;
            } else {
                //判断是否在数组中
                if (array_search($czy_add, $czy_all) > 0) {
                    //在数组中继续执行
                    continue;
                } else {
                    //判断编号是否被别人占用
                    $bianhao = 'CZY' . $czy_add;
                    $res = Db::name('jujian')->where('bh', $bianhao)->select();
                    if (count($res) > 0) {
                        continue;
                    } else {
                        $bh = $bianhao;
                        break;
                    }
                }
            }
        }
        if (!isset($bh)) {
            returnError('操作员人数已达到上限');
        }
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $shuju = array();
        $shuju['bh'] = $bh;
        $shuju['xingming'] = $data['xingming'];
        $shuju['passwd'] = md5(888888);
        $shuju['tel'] = $data['tel'];
        $shuju['lb_id'] = $data['qx'];
        $shuju['par_id'] = $user_id;
        $shuju['bz'] = 1;
        $shuju['sj_xulie'] = ',' . $user_id . $this->jujian['sj_xulie'];
        $result = db('jujian')->insertGetId($shuju);
        if ($result > 0) {
            $operation_category = 30;
            $detail_name = array('添加操作员', '操作员编号', '操作员姓名', '操作员电话号码');
            $operation_value = array('成功', $bh, $data['xingming'], $data['tel']);
            $re_name = 'czy_add';
            $re_value = '1';
            $rizhi = new Rizhi();
            $jieguo = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if ($jieguo['code'] == '1') {
                returnSuccess($jieguo);
            }
        } else {
            returnError('添加操作员失败，请重试');
        }

    }

    //操作员管理编辑数据
    public function czygl_bj_shuju()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError('请选择要编辑的操作员ID');
        }
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $guanli = db('jujian')
            ->alias('j')
            ->join('jujian_lb jl', 'jl.id=j.lb_id')
            ->field('j.id,j.bh,j.tel,jl.name')
            ->where('j.id', $data['bjdl_id'])
            ->find();
        $result_guanli_lb = db('jujian_lb')
            ->where('jujian_id', $user_id)
            ->field('id,name')
            ->select();
        $result['info'] = $guanli;
        $result['info_lb'] = $result_guanli_lb;
        if (!empty($result)) {
            returnSuccess($result);
        } else {
            returnError('暂未数据');
        }
    }

    //操作员管理编辑提交
    public function czygl_bj(Request $requert)
    {
        $data = input();
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $data['qx'] = input('qx/d');
        if (!$data['qx']) {
            returnError('权限模板不能为空');
        }
        $data['bjdl_id'] = input('bjdl_id/d');
        if (!$data['bjdl_id']) {
            returnError('请选择编辑的操作员ID');
        }
        $data['xingming'] = input('xingming');
        if (!$data['xingming']) {
            returnError('操作员姓名不能为空');
        }
        $data['tel'] = input('tel');
        if (!$data['tel']) {
            returnError('手机号不能为空');
        }
        $user = db('jujian')->where('id', $data['bjdl_id'])->field('xingming,tel')->find();
        if ($user['tel'] != $data['tel']) {
            $tel_all = db('jujian')
                ->where('tel', $data['tel'])
                ->where('sj_xulie', 'like', "%," . $user_id . ",%")
                ->count();
            if ($tel_all > 0) {
                returnError('该手机号码已被注册');
            }
        }
        preg_match('/\d+/', $data['qx'], $lb_id);
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['xingming' => $data['xingming'], 'tel' => $data['tel'], 'lb_id' => $lb_id[0], 'passwd' => md5(888888)]);
        if ($result > 0) {
            $operation_category = 31;
            $detail_name = array('编辑操作员', '操作员ID', '操作员姓名', '操作员电话号码', '操作者编号');
            $operation_value = array('成功', $data['bjdl_id'], $data['xingming'], $data['tel'], $data['xingming']);
            $re_name = 'czy_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $jieguo = $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if ($jieguo['code'] == '1') {
                returnSuccess($result);
            }
        } else {
            returnError('您未做任何修改');
        }
    }

    //操作员管理重置密码
    public function czygl_czmm(Request $request)
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (empty($data['bjdl_id'])) {
            returnError('请选择要重置密码的操作员ID');
        }

        $is_chongfu = db('jujian')->where('id', $data['bjdl_id'])->value('passwd');
        if ($is_chongfu == md5(888888)) {
            returnError('重置密码失败,您当前的密码为888888');
        }
        $result = db('jujian')->where('id', $data['bjdl_id'])->update(['passwd' => md5(888888)]);
        if ($result > 0) {
            if ($this->isCZY) {
                $user_id = $this->par_id;
            } else {
                $user_id = $this->id;
            }
            $operation_category = 109;
            $detail_name = array('修改代理或操作员密码', '管理员ID', '密码');
            $operation_value = array('成功', $data['bjdl_id'], '888888');
            $re_name = 'tell_passwd_edit';
            $re_value = '1';
            $rizhi = new Rizhi();
            $res = $rizhi->index($this->id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            if ($res['code'] == '1') {
                returnSuccess($res);
            }
        } else {
            returnError('重置密码失败');
        }
    }

    //删除柜员
    public function czygl_scgy()
    {
        $data = input();
        $data['scgy_id'] = input('scgy_id/d');
        if (empty($data['scgy_id'])) {
            returnError('请选择要删除的操作员ID');
        }
        $res = db('jujian')
            ->where('id', $data['scgy_id'])
            ->update(['bz' => 3]);
        if (!empty($res)) {
            $this->riZhi(59, ['删除柜员' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['scgy_id']], ['user_add' => '1']);
            returnSuccess($res);
        } else {
            returnError('删除失败');
        }
    }

    //代理审核数据
    public function dlsh_shuju()
    {
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $lb = db('jujian')
            ->where('id', $user_id)
            ->field('par_id,id')
            ->find();
        if ($lb['par_id'] == 0) {
            $result = db('jujian')
                ->where('bz', 0)
                ->where('sj_xulie', 'like', '%,' . $user_id . ',%')
                ->select();
            if (!empty($result)) {
                foreach ($result as $k => &$val) {
                    $result[$k]['bz'] = '未审核';
                    $result[$k]['beizhu'] = '';
                }
                returnSuccess($result);
            } else {
                returnError('暂无数据');
            }
        } else {
            //查询bz状态为0或者2的数据
            $map = array();
            $map['bz'] = array(['=', 0], ['=', 2], 'or');
            $result = db('jujian')
                ->where($map)
                ->where('sj_xulie', 'like', '%,' . $user_id . ',%')
                ->select();
            if (!empty($result)) {
                foreach ($result as $k => &$val) {
                    if ($val['bz'] == 0) {
                        $result[$k]['bz'] = '未审核';
                    } else {
                        $result[$k]['bz'] = '已拒绝';
                    }
                    $result[$k]['beizhu'] = '';
                }
                returnSuccess($result);
            } else {
                returnError('暂无数据');
            }
        }
    }

    //单个代理审核
    public function dlsh_sh()
    {
        $xz = input('xz/d');
        if (!$xz) {
            returnError('请选中要审核的代理');
        }
        if ($this->isCZY) {
            $user_id = $this->par_id;
        } else {
            $user_id = $this->id;
        }
        $jujian = db('jujian')->where('id', $xz)->field('id,xingming,bh,dizhi,tel,fzr_name,fzr_bh,bank_id,bank_bh,sheng_id,shi_id,fee_zu_id,hb_zu_id,toucun_zu_id,rujin_zu_id,chujin_zu_id,par_id,beizhu')->find();
        if (!$jujian) {
            returnError('代理不存在');
        }
        $pbh = db('jujian')->where('id', $jujian['par_id'])->field('bh as pbh,xingming as pxingming,par_id as pids')->find();//拿到上级编号
        $jujian['par_id'] = $pbh['pbh'];
        $jujian['par_name'] = $pbh['pxingming'];
        $is_xianshi = db('jujian')->where('id', $user_id)->value('par_id');
        if ($is_xianshi == '0') {
            $data['is_xianshi'] = '1';
        } else {
            $data['is_xianshi'] = '0';
        }
        $gt_jujian_id = db('jujian')->where('id', $user_id)->value('gt_jujian_id');
        if (!$gt_jujian_id) {
            returnError('顶级代理不存在');
        }
        $data['sheng'] = db('sheng')->field('id,sheng')->select();
        $data['shi'] = db('shi')->where('sheng_id', $jujian['sheng_id'])->field('id,shi')->select();
        $data['bank'] = db('bank')->field('id,name')->select();
        $data['fee_jujian_zu'] = db('fee_jujian_zu')->where('ib_id', $gt_jujian_id)->field('id,name')->select();
        $data['toucun_zu'] = db('toucun_zu')->where('ib_id', $gt_jujian_id)->field('id,name')->select();
        $data['rujin_zu'] = db('rujin_zu')->where('ib_id', $gt_jujian_id)->field('id,name')->select();
        $data['chujin_zu'] = db('chujin_zu')->where('ib_id', $gt_jujian_id)->field('id,name')->select();
        $data['huobi_zu'] = db('huobi_zu')->where('ib_id', $gt_jujian_id)->field('id,name')->select();
        $data['jujian'] = $jujian;

        returnSuccess($data);
    }

    //代理审核
    public function dlsh()
    {
        $data = input();
        $data['id'] = input('id/d');
        if (!$data['id']) {
            returnError('代理ID不能为空');
        } else {
            $dl_id = $data['id'];
        }
        $cbmb = input('cbmb/d');  //成本模板
        if (!$cbmb) {
            returnError('请选择成本模板');
        }

        $tcmb = input('tcmb/d');
        if (!$tcmb) {
            returnError('请选择头寸模板');
        }

        $chujinzu = input('chujinzu/d');
        if (!$chujinzu) {
            returnError('请选择出金模板');
        }

        $rujinzu = input('rujinzu/d');
        if (!$rujinzu) {
            returnError('请选择入金模板');
        }

        $huobizu = input('huobizu/d');
        if (!$rujinzu) {
            returnError('请选择汇率模板');
        }
        if (input('chongshen/d') == 0) {
            $re = db('jujian')->where('id', $data['id'])->update(['bz' => 0]);
            if ($re) {
                $this->riZhi(25, ['代理审核驳回' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['id']], ['user_add' => '1']);
                returnSuccess('重审成功');
                die;
            } else {
                returnError('重审失败');
            }

        }

        $moban = db('jujian')->where('id', $dl_id)->find();
        //上级代理ID
        $dl_id_par_id = db('jujian')->where('id', $dl_id)->value('par_id');
        //上级代理的模板权限
        $par_id_qx = db('jujian')->where('id', $dl_id_par_id)->find();
        //如果上级是顶级代理直接审核通过不做对比
        $shuju = array(
            'bz' => 1
        , 'fee_zu_id' => $cbmb
        , 'toucun_zu_id' => $tcmb
        , 'chujin_zu_id' => $chujinzu
        , 'rujin_zu_id' => $rujinzu
        , 'hb_zu_id' => $huobizu
        );
        Db::startTrans();
        if ($par_id_qx['lb_id'] == '1') {
            $jieguo = db('jujian')->where('id', $dl_id)->update($shuju);
            if ($jieguo) {
                $is_bian = db('jujian_bian')->where('yh_id', $dl_id)->select();
                if (empty($is_bian)) {
                    $jujian_bian_shuju = array(['yh_id' => $dl_id, 'hb_id' => 1], ['yh_id' => $dl_id, 'hb_id' => 2], ['yh_id' => $dl_id, 'hb_id' => 3], ['yh_id' => $dl_id, 'hb_id' => 4]);
                    $isadd = db('jujian_bian')->insertAll($jujian_bian_shuju);
                    if ($isadd) {
                        Db::commit();
                        $this->riZhi(24, ['代理审核通过' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['id']], ['user_add' => '1']);
                        returnSuccess('审核成功');
                    } else {
                        Db::rollback();
                        returnError('审核失败');
                    }
                } else {
                    Db::commit();
                    $this->riZhi(24, ['代理审核通过' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['id']], ['user_add' => '1']);
                    returnSuccess('审核成功');
                }
            } else {
                Db::rollback();
                returnError('您未做任何修改');
            }
        } else {
            if ($par_id_qx['lb_id'] != 1 && $moban['fee_zu_id'] != $cbmb) {
                $user_heyues = db('fee_jujian_zu_detail')->where('fee_zu_id', $cbmb)->select();

                //用户传递的头寸模板
                $user_toucun = db('toucun_zu')->where('id', $tcmb)->find();
                //上级的头寸模板
                $par_toucun = db('toucun_zu')->where('id', $par_id_qx['toucun_zu_id'])->find();
                if ($user_toucun && $par_toucun) {
                    if ($user_toucun['chengben'] > $par_toucun['chengben']) {
                        Db::rollback();
                        returnError('头寸模板不能小于上级！请重新选择');
                    }
                }
                //比较上级手续费模板
                foreach ($user_heyues as $k => $v) {
                    $max = db('jujian')
                        ->alias('j')
                        ->where('j.id', $dl_id_par_id)
                        ->join('fee_jujian_zu_detail fjd', 'fjd.fee_zu_id = j.fee_zu_id and fjd.heyue_zu_id = ' . $v['heyue_zu_id'], 'LEFT')
                        ->join('fee_jujian_zu fj', 'fj.ib_id = j.gt_jujian_id and fj.moren_bz = 1', 'LEFT')
                        ->join('fee_jujian_zu_detail fjd1', 'fjd1.fee_zu_id = fj.id and fjd1.heyue_zu_id = ' . $v['heyue_zu_id'], 'LEFT')
                        ->field("if(`fjd`.`jian_yongjin`,`fjd`.`jian_yongjin`,`fjd1`.`jian_yongjin`) as jian_yongjin,if(`fjd`.`ping_zuo_yongjin`,`fjd`.`ping_zuo_yongjin`,`fjd1`.`ping_zuo_yongjin`) as ping_zuo_yongjin,if(`fjd`.`ping_jin_yongjin`,`fjd`.`ping_jin_yongjin`,`fjd1`.`ping_jin_yongjin`) as ping_jin_yongjin")
                        ->find();
                    if ($v['jian_yongjin'] < $max['jian_yongjin'] || $v['jian_yongjin'] < $max['jian_yongjin'] || $v['ping_zuo_yongjin'] < $max['ping_zuo_yongjin']) {
                        Db::rollback();
                        returnError("错误：成本金额小于上级（建佣金：{$v['jian_yongjin']}平今佣金：{$v['ping_zuo_yongjin']} 平昨佣金：{$v['ping_zuo_yongjin']}）小于上级费率（建佣金：{$max['jian_yongjin']}平今佣金：{$max['ping_jin_yongjin']} 平昨佣金：{$max['ping_zuo_yongjin']}）");
                    }
                    $sql = "SELECT min(`jian_yongjin`) as mjy,min(`ping_zuo_yongjin`) as pzy,min(`ping_jin_yongjin`) as pjy FROM `fee_jujian_zu_detail` WHERE `fee_zu_id` IN (select fee_zu_id from jujian where par_id = $dl_id) AND `heyue_zu_id` = {$v['heyue_zu_id']}";
                    $min = db()->query($sql);
                    if ($v['jian_yongjin'] < $min[0]['mjy'] || $v['jian_yongjin'] < $min[0]['pzy'] || $v['ping_jin_yongjin'] < $min[0]['pjy']) {
                        Db::rollback();
                        returnError("错误：成本金额大于下级（建佣金：{$v['jian_yongjin']}平今佣金：{$v['ping_zuo_yongjin']} 平昨佣金：{$v['ping_zuo_yongjin']}）小于上级费率（建佣金：{$min[0]['mjy']}平今佣金：{$min[0]['pjy']} 平昨佣金：{$min[0]['pzy']}）");
                    }
                }
            }
            $jieguo = db('jujian')->where('id', $dl_id)->update($shuju);
            if ($jieguo) {
                $is_bian = db('jujian_bian')->where('yh_id', $dl_id)->select();
                if (empty($is_bian)) {
                    $jujian_bian_shuju = array(['yh_id' => $dl_id, 'hb_id' => 1], ['yh_id' => $dl_id, 'hb_id' => 2], ['yh_id' => $dl_id, 'hb_id' => 3], ['yh_id' => $dl_id, 'hb_id' => 4]);
                    $isadd = db('jujian_bian')->insertAll($jujian_bian_shuju);
                    if ($isadd) {
                        Db::commit();
                        $this->riZhi(24, ['代理审核通过' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['id']], ['user_add' => '1']);
                        returnSuccess('审核成功');
                    } else {
                        Db::rollback();
                        returnError('审核失败');
                    }
                } else {
                    Db::commit();
                    $this->riZhi(24, ['代理审核通过' => '成功', '操作人员' => $this->jujian['bh'], '柜员ID' => $data['id']], ['user_add' => '1']);
                    returnSuccess('审核成功');
                }
            } else {
                Db::rollback();
                returnError('您未做任何修改');
            }
        }
    }

    //代理审核驳回
    public function dlsh_bh()
    {
        $data = input();
        if (input('xz/d') == 0) {
            return json_encode(['code' => 0, 'msg' => '请选择要驳回的代理']);
        }
        $result = db('jujian')->where('id', $data['xz'])->update(['bz' => 2]);
        $yonghu = db('jujian')->where('id', $data['xz'])->field('id,bh,xingming')->find();
        if ($result) {
            $user_id = $this->id;
            $operation_category = 23;
            $detail_name = array('代理审核驳回', '审核操作者ID', '用户ID', '用户编号', '用户姓名');
            $operation_value = array('驳回', $user_id, $yonghu['id'], $yonghu['bh'], $yonghu['xingming']);
            $re_name = 'user_check_refuse';
            $re_value = '1';
            $rizhi = new Rizhi();
            $rizhi->index($user_id, $operation_category, $detail_name, $operation_value, $re_name, $re_value);
            returnSuccess('代理驳回成功');
        } else {
            returnError('代理驳回失败');
        }
    }

    //代理审核删除
    public function dlsh_sc()
    {
        $data = input();
        if (input('xz/d') == 0) {
            returnError('请选择要删除的代理');
        }
        $result = db('jujian')->where('id', $data['xz'])->update(['bz' => 3]);
        if ($result) {
            returnSuccess('代理删除成功');
        } else {
            returnError('代理删除失败');
        }

    }

    //编辑代理
    public function bjdl()
    {
        $data = input();
        $data['bjdl_id'] = input('bjdl_id/d');
        if (!$data['bjdl_id']) {
            returnError('该用户ID不存在');
        }
        $bjdl_id = $data['bjdl_id'];
        //用户信息
        $info = db('jujian')
            ->alias('j')
            ->join('jujian_lb jl', 'j.lb_id=jl.id', 'LEFT')
            ->join('sheng s', 's.id=j.sheng_id', 'LEFT')
            ->join('shi si', 'si.id=j.shi_id', 'LEFT')
            ->join('bank b', 'b.id=j.bank_id', 'LEFT')
            ->join('fee_jujian_zu fz', 'fz.id=j.fee_zu_id and j.gt_jujian_id=fz.ib_id', 'LEFT')
            ->join('huobi_zu hz', 'hz.id=j.hb_zu_id and j.gt_jujian_id=hz.ib_id', 'LEFT')
            ->join('toucun_zu tz', 'tz.id=j.toucun_zu_id and j.gt_jujian_id=tz.ib_id', 'LEFT')
            ->join('rujin_zu rz', 'rz.id=j.rujin_zu_id and j.gt_jujian_id=rz.ib_id', 'LEFT')
            ->join('chujin_zu cz', 'cz.id=j.chujin_zu_id and j.gt_jujian_id=cz.ib_id', 'LEFT')
            ->join('jujian ju', 'ju.id=j.par_id', 'LEFT')
            ->join('fanyong_lb fl', 'fl.id =  tz.fanyong_lb', 'LEFT')
            ->where('j.id', $bjdl_id)
            ->field('jl.id as lb_id,j.id,j.fzr_bh,j.bank_id,j.xingming,ju.bh as par_bh,j.fzr_name,j.tel,j.yonghu_num,j.fzr_bh,s.sheng,s.id as sid,si.shi,si.id as siid,b.name as khh,j.dizhi,j.bank_bh,fz.name as fzmb,hz.name as hlmb,tz.name as tcmb,rz.name as rjmb,cz.name as cjmb,j.bh,fz.id as fid,hz.id as hid,tz.id as tid,rz.id as rid,cz.id as cid,fl.name as fanyong')
            ->find();
        if (!empty($info)) {
            returnSuccess($info);
        } else {
            returnError('暂无数据');
        }
    }

    //编辑代理提交
    public function bjdl_tj()
    {
        $data = input();
        $bjdl_id = input('bjdl_id/d');
        $lb_id = input('lb_id/d');
        $xingming = input('xingming');
        $fzr_name = input('fzr_name');
        $tel = input('tel');
        $yonghu_num = input('yonghu_num');
        $fzr_bh = input('fzr_bh');
        $sheng_id = input('sheng_id/d');
        $shi_id = input('shi_id/d');
        $bank_id = input('bank_id/d');
        $dizhi = input('dizhi');
        $bank_bh = input('bank_bh');
        $par_bh = input('par_bh');
        $fee_zu_id = input('fee_zu_id/d', 1);
        $hb_zu_id = input('hb_zu_id/d', 1);
        $tcmb = input('tcmb/d', 1);
        $rjmb = input('rjmb/d', 1);
        $cjmb = input('cjmb/d', 1);
        $fanyong_lb = input('fanyong_lb/d', 1);
        //上级代理的编号
//        ******************************验证参数***************************
        //上级代理ID
        $dl_id_par_id = db('jujian')->where('id', $bjdl_id)->where('bz', 1)->value('par_id');
        //上级代理的模板权限
        $par_id_qx = db('jujian')
            ->where('id', $dl_id_par_id)
            ->where('bz', 1)
            ->find();
        $message['lb_id'] = $lb_id;
        $message['xingming'] = $xingming;
        $message['fzr_name'] = $fzr_name;
        $message['tel'] = $tel;
        $message['yonghu_num'] = $yonghu_num;
        $message['fzr_bh'] = $fzr_bh;
        $message['sheng_id'] = $sheng_id;
        $message['shi_id'] = $shi_id;
        $message['bank_id'] = $bank_id;
        $message['dizhi'] = $dizhi;
        $message['bank_bh'] = $bank_bh;
        $message['fee_zu_id'] = $fee_zu_id;
        $message['hb_zu_id'] = $hb_zu_id;
        $message['toucun_zu_id'] = $tcmb;
        $message['rujin_zu_id'] = $rjmb;
        $message['chujin_zu_id'] = $cjmb;
//        $message['fanyong_lb'] = $fanyong_lb;
        //如果上级是顶级代理直接审核通过不做对比
        if ($par_id_qx['lb_id'] == '1') {
            $jieguo = db('jujian')
                ->where('id', $bjdl_id)
                ->update($message);

            if ($jieguo) {
                returnSuccess('审核成功');
                die;
            } else {
                returnError('审核失败，你未做任何修改');
            }
        } else {
            //用户当前模板
            $user = db('jujian')->where('id', $bjdl_id)->find();
            $user_heyues = db('fee_jujian_zu_detail')->where('fee_zu_id', $fee_zu_id)->select();
            //用户传递的头寸模板
            $user_toucun = db('toucun_zu')->where('id', $tcmb)->find();
            //上级的头寸模板
            $par_toucun = db('toucun_zu')->where('id', $par_id_qx['toucun_zu_id'])->find();
            if ($user_toucun && $par_toucun) {
                if ($user_toucun['chengben'] > $par_toucun['chengben']) {
                    returnError('头寸模板不能小于上级！请重新选择');
                }
            }
            if ($par_id_qx['lb_id'] != 1 && $user['fee_zu_id'] != $fee_zu_id) {
                //比较上级手续费模板
                foreach ($user_heyues as $k => $v) {
                    $max = db('jujian')
                        ->alias('j')
                        ->where('j.id', $dl_id_par_id)
                        ->join('fee_jujian_zu_detail fjd', 'fjd.fee_zu_id = j.fee_zu_id and fjd.heyue_zu_id = ' . $v['heyue_zu_id'], 'LEFT')
                        ->join('fee_jujian_zu fj', 'fj.ib_id = j.gt_jujian_id and fj.moren_bz = 1', 'LEFT')
                        ->join('fee_jujian_zu_detail fjd1', 'fjd1.fee_zu_id = fj.id and fjd1.heyue_zu_id = ' . $v['heyue_zu_id'], 'LEFT')
                        ->field("if(`fjd`.`fee_zu_id`,`fjd`.`fee_zu_id`,`fjd1`.`fee_zu_id`) as fee_zu_id,if(`fjd`.`jian_yongjin`,`fjd`.`jian_yongjin`,`fjd1`.`jian_yongjin`) as jian_yongjin,if(`fjd`.`ping_zuo_yongjin`,`fjd`.`ping_zuo_yongjin`,`fjd1`.`ping_zuo_yongjin`) as ping_zuo_yongjin,if(`fjd`.`ping_jin_yongjin`,`fjd`.`ping_jin_yongjin`,`fjd1`.`ping_jin_yongjin`) as ping_jin_yongjin")
                        ->find();
                    if ($v['jian_yongjin'] < $max['jian_yongjin'] || $v['ping_zuo_yongjin'] < $max['ping_zuo_yongjin'] || $v['ping_jin_yongjin'] < $max['ping_jin_yongjin']) {
                        $name = db('fee_jujian_zu')->where('id', $max['fee_zu_id'])->value('name');
                        returnError("错误：上级模板:{$name}。手续费金额小于上级（建佣金：{$v['jian_yongjin']}平今佣金：{$v['ping_zuo_yongjin']} 平昨佣金：{$v['ping_zuo_yongjin']}）小于上级费率（建佣金：{$max['jian_yongjin']}平今佣金：{$max['ping_jin_yongjin']} 平昨佣金：{$max['ping_zuo_yongjin']}）");
                    }
                    $sql = "SELECT fee_zu_id, min(`jian_yongjin`) as mjy,min(`ping_zuo_yongjin`) as pzy,min(`ping_jin_yongjin`) as pjy FROM `fee_jujian_zu_detail` WHERE `fee_zu_id` IN (select fee_zu_id from jujian where par_id = $bjdl_id) AND `heyue_zu_id` = {$v['heyue_zu_id']}";
                    $min = db()->query($sql);
                    if (!empty($min) && $min[0]['mjy'] != null && $min[0]['pzy'] != null && $min[0]['pjy'] != null) {
                        if ($v['jian_yongjin'] > $min[0]['mjy'] || $v['ping_zuo_yongjin'] > $min[0]['pzy'] || $v['ping_jin_yongjin'] > $min[0]['pjy']) {
                            $name = db('fee_jujian_zu')->where('id', $min[0]['fee_zu_id'])->value('name');
                            returnError("错误：下级模板:{$name}。手续费金额大于下级（建佣金：{$v['jian_yongjin']}平今佣金：{$v['ping_zuo_yongjin']} 平昨佣金：{$v['ping_zuo_yongjin']}）大于下级（建佣金：{$min[0]['mjy']}平今佣金：{$min[0]['pjy']} 平昨佣金：{$min[0]['pzy']}）");
                        }
                    }
                }
            }
            $jieguo = db('jujian')
                ->where('id', $bjdl_id)
                ->update($message);
            if ($jieguo) {
                returnSuccess('审核成功');
                die;
            } else {
                returnError('审核失败，你未做任何修改');
            }
        }


    }

}

?>